﻿using System.Threading.Tasks;
using AvaloniaApplication1.Component.ViewModel;
using AvaloniaApplication1.IServices;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;

namespace AvaloniaApplication1.ViewModels.ModbusCardViewModel;

public partial class SlaveViewModel:ObservableObject
{
    [ObservableProperty]
    private byte _slaveId=1;
    [ObservableProperty]
    private ushort _slaveStartAddress;
    [ObservableProperty]
    private ushort _slaveCount;
    [ObservableProperty]
    private string _deviceName;
    [ObservableProperty]
    private int _intervalTime;
    [ObservableProperty] private IModbusManager _modbusManager;
    // 引用 InfoBar 组件的 ViewModel
    [ObservableProperty] private InfoViewModel _inforBar;
    
    public SlaveViewModel(string deviceName,IModbusManager modbusManager)
    {
        DeviceName = deviceName;
        ModbusManager = modbusManager;
        InforBar = new InfoViewModel();//Dilog应该也可以是这样new,这样就不会出现一个弹窗未关闭无法弹出
        var modbusConfigs =  ModbusManager.GetModbusDevice(DeviceName);
        SlaveId=modbusConfigs.SlaveInfo.SlaveId;
        SlaveStartAddress=modbusConfigs.SlaveInfo.StartAddress;
        SlaveCount=modbusConfigs.SlaveInfo.ReadRegisterCount;
        IntervalTime=modbusConfigs.SlaveInfo.IntervalTime;
    }
    
    [RelayCommand]
    public async Task SaveSlave()
    {
        var result = await ModbusManager.SlaveConfigureDeviceAsync(DeviceName,SlaveId, SlaveStartAddress, SlaveCount, IntervalTime);
        InforBar.ShowInfo(result ? "保存成功" : "保存失败");
       //  var modbusConfigs =  ModbusManager.GetModbusDevice(DeviceName);
       // var newslave= modbusConfigs.SlaveInfo;
       
    }
    
    
}